package xyz.wpxy.wxpushmsg.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import xyz.wpxy.wxpushmsg.common.ExpiryMap;
import xyz.wpxy.wxpushmsg.constant.WxMsgConstant;
import xyz.wpxy.wxpushmsg.entity.WxConfig;
import xyz.wpxy.wxpushmsg.utils.HttpClientUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @author: Peng Wei
 * @date:2023/8/7 15:59
 */
@Slf4j
@Service
@AllArgsConstructor
public class WxPushMsgService {

    public static ExpiryMap expiryMap = new ExpiryMap(true);

    public final WxConfig wxConfig;

    public String getAccessToken() {
        //获取token
        String url = wxConfig.getAccessTokenUrl()
                .replaceAll("CORPID", wxConfig.getCorpid())
                .replaceAll("CORPSECRET", wxConfig.getCorpsecret());
        //请求获取token:
        String result = HttpClientUtils.get(url);
        log.info("获取token的值为:{}", result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String accessToken = null;
        //判断缓存中是否有token:
        if (!expiryMap.containsKey("token")) {
            //从缓存Map中提取token:
            accessToken = jsonObject.getString("access_token");
            expiryMap.put("token", accessToken, WxMsgConstant.EXPIRY_TIME);
            log.info("缓存map已过期或不存在，正在获取token");
        } else {
            accessToken = expiryMap.get("token").toString();
            log.info("正在从缓存map中读取token");
        }
        //获取token:
        return accessToken;
    }

    /**
     * 根据电话号码获取userId
     *
     * @param token
     * @param employeePhone
     * @return
     */
    public String getUserId(String token, String employeePhone) {
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\"mobile\":" + "\"" + employeePhone + "\"");
        sb.append("}");
        String json = sb.toString();
        String result = "";
        String url = wxConfig.getGetUseridUrl() + token;

        try {
            HttpsURLConnection http = getPostHttp(url, "");
            OutputStream os = http.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            result = new String(jsonBytes, "UTF-8");
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        log.info("获取用户信息结果为:{}", jsonObject);
        return jsonObject.getString("userid");
    }

    public static HttpsURLConnection getPostHttp(String action, String token) throws Exception {
        URL url = null;
        HttpsURLConnection http = null;
        try {
            url = new URL(action);
            http = (HttpsURLConnection) url.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            if (StringUtils.isEmpty(token)) {
                http.setRequestProperty("token", token);
            }
            http.setDoOutput(true);
            http.setDoInput(true);
            //连接超时30秒
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            //读取超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return http;
    }

    /**
     * 发送微信消息
     *
     * @param token
     * @param json
     * @return
     */
    public String sendMessage(String token, String json) {
        //请求链接
        String action = wxConfig.getSendMessageUrl() + token;
        try {
            return HttpClientUtils.httpClientByPost(action, json);
        } catch (Exception e) {
            e.printStackTrace();
            return "请求失败";
        }
    }

    /**
     * 获取微信所有用户
     *
     * @return
     */
    public List<JSONObject> getWechatAllUser() {
        // 获取token
        String token = getAccessToken();
        String template = wxConfig.getGetUserListUrl() + "?access_token=%s&department_id=1&fetch_child=1";
        String str = String.format(template, token);
        String userResult = HttpClientUtils.get(str);
        JSONObject jsonUser = JSON.parseObject(userResult);
        // 返回结果
        List<JSONObject> resultJsonList = new ArrayList<>();
        if ("0".equals(jsonUser.getString("errcode"))) {
            String userListStr = jsonUser.getString("userlist");
            JSONArray userList = JSON.parseArray(userListStr);
            resultJsonList = JSONObject.parseArray(JSON.toJSONString(userList.size()), JSONObject.class);
            return resultJsonList;
        } else {
            return resultJsonList;
        }
    }
}
